package com.hongxun.design.jungong.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.fragments.BaseFragment;
import com.hongxun.design.jungong.activity.ShowBigImageActivity1;
import com.hongxun.design.jungong.adapter.Adapter_FragMaterial;
import com.hongxun.design.jungong.dialog.FixMaterialFaultDialog;
import com.hongxun.design.jungong.model.MaterialDetail;
import com.hongxun.design.jungong.model.MatreialDetailSys;
import com.hongxun.design.jungong.utils.IntentUtil;
import com.hongxun.design.jungong.utils.jxlUtil;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.AddNewMaterial;
import com.hongxun.design.ui.SettingTypeActivity;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.DialogUtils;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.lidroid.xutils.http.RequestParams;
import com.pop.android.common.util.ToastUtils;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在线：导入项目材料
 */

public class FragmentMaterial extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private View view;
    private HeadSecondControlPanel headsecond_layout;
    private SwipeRefreshListView refreshListView;
    private Adapter_FragMaterial adaptermaterial;
    private ArrayList<MaterialDetail> detailList;
    private boolean isRefresh = true;
    private int startNum = 0;
    private int addNum = MyApp.addNum;
    private TextView sync_button, errNumTv;
    private LinearLayout layoutMainView, layButt;
    /**
     * @parm 0切换项目
     * @parm 1导入材料
     * @parm 2初次进入
     */
    private int type = 2;
    //
    private ArrayList<String> arrayList;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED://提交项目材料后，获取到材料版本
                    String valueOf = String.valueOf(msg.obj);
                    //正确的时候(不含code，msg)
                    if (FastJsonUtil.JsonToCheck(valueOf)) {
                        if (valueOf.contains(":")) {
                            String ver_ID = valueOf.substring(valueOf.lastIndexOf(":") + 1, valueOf.length() - 1).trim();
                            MyApp.currProject.setCodeset_version_id(ver_ID);
                            isArrowAdd = false;
                            getCodeSetList(2);
                        }
                    } else {
                        showToast(FastJsonUtil.JsonToCheck_String(String.valueOf(msg.obj)));
                        hideWaitIngDialog();
                    }
                    break;
                case 1://下拉刷新数据
                case 2://下载项目材料
                case HttpStringUtil.ADDMROE://加载更多
                    if (null != msg.obj) jsonToData(msg.what, String.valueOf(msg.obj));
                    else hideWaitIngDialog();
                    break;
                case 3://手动导入数据
                    String valueOf1 = String.valueOf(msg.obj);
                    if (valueOf1.endsWith("2")) {//手动选取
                        Intent intent = IntentUtil.showFileChooser(1);
                        getActivity().startActivityForResult(intent, 2);
                    } else if (valueOf1.endsWith("1")) {//QQ
                        if (fileList_QQ.isEmpty()) {
                            ToastShow.showShort(getActivity(), "没有自动找到文件夹,请手动选取");
                            return false;
                        }
                        ArrayList<String> arrayList = new ArrayList<>();
                        for (File file : fileList_QQ) {
                            String path = file.getPath();
                            int index = path.lastIndexOf("/") + 1;
                            String name = path.substring(index, path.length());
                            arrayList.add(name);
                        }
                        PopwindowUtil.popChoice_JG_file(getActivity(), layoutMainView, arrayList, handler, 4);
                    } else if (valueOf1.endsWith("0")) {//微信
                        if (fileList_WX.isEmpty()) {
                            ToastShow.showShort(getActivity(), "没有自动找到文件夹,请手动选取");
                            return false;
                        }
                        ArrayList<String> arrayList = new ArrayList<>();
                        for (File file : fileList_WX) {
                            String path = file.getPath();
                            int index = path.lastIndexOf("/") + 1;
                            String name = path.substring(index, path.length());
                            arrayList.add(name);
                        }
                        PopwindowUtil.popChoice_JG_file(getActivity(), layoutMainView, arrayList, handler, 5);
                    }
                    break;
                case 4://选择了QQ文件
                    String valueOf4 = String.valueOf(msg.obj);
                    File file4 = fileList_QQ.get(Integer.valueOf(valueOf4));
                    dellFile(file4);
                    break;
                case 5://选择了微信文件
                    String valueOf5 = String.valueOf(msg.obj);
                    File file5 = fileList_WX.get(Integer.valueOf(valueOf5));
                    dellFile(file5);
                    break;
                case 765://修改了一个数据
                    errNumTv.setText("错误：" + errList.size());
                    detailList.add(0, (MaterialDetail) msg.obj);
                    refreshListView.update();
                    refreshListView.setCanScroll(false);
                    layButt.setVisibility(View.VISIBLE);
                    break;
                case 10://导入数据
                    PopwindowUtil.popChoice_JG_file(getActivity(), layoutMainView, arrayList, handler, 3);
                    break;
                case 11://nx把提交后的项目材料缓存到xml
                    List<MatreialDetailSys> toGetT = FastJsonUtil.getMaterialList(String.valueOf(msg.obj));
                    Context context = getActivity().getApplicationContext();
                    ShardPreferencesTool.save(context, MString.nxMaterialImp, FastJsonUtil.beanToJson(toGetT), 3);
                    break;
            }
            return false;
        }
    });

    private void jsonToData(int i, String json) {
        getCodeSetList(11);//获取全部数据
        List<MatreialDetailSys> toGetT = FastJsonUtil.getMaterialList(json);
        if (null != toGetT) {
            switch (i) {
                case 100://加载更多
                    if (toGetT.isEmpty()) showToast("加载完成！");
                    refreshListView.setRefreshing(false);
                    refreshListView.removeFooterView();
                    break;
                case 1://下拉
                    if (toGetT.isEmpty()) showToast("此项目还没有数据！");
                    detailList.clear();
                    refreshListView.setRefreshing(false);
                    break;
                case 2://下载项目材料
                    if (toGetT.isEmpty()) showToast("此项目还没有数据！");
                    detailList.clear();
                    isRefresh = true;
                    refreshListView.setCanScroll(true);
                    layButt.setVisibility(View.GONE);
                    break;
            }

            if (!toGetT.isEmpty()) {
                sync_button.setText("添加新的材料");
                layButt.setVisibility(View.VISIBLE);
            }
            for (MatreialDetailSys detailSys : toGetT) {
                MaterialDetail detail = new MaterialDetail();
                detail.setNum(String.valueOf(detailSys.getNum()));
                detail.setUnit(String.valueOf(detailSys.getUnit()));
                detail.setSpec(String.valueOf(detailSys.getSpec()));
                detail.setMaterial_number(String.valueOf(detailSys.getErp_code()));
                detail.setName(String.valueOf(detailSys.getName()));
                detail.setType(String.valueOf(detailSys.getType()));
                detail.setSort(detailSys.getSort());
                detailList.add(detail);
            }
            if (type == 2 && detailList.size() > 0) {//初次进入获取数据则不能进行数据添加
                isArrowAdd = false;
            }
            refreshListView.update();
        }
        hideWaitIngDialog();
    }

    boolean isArrowAdd = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.jg_fragmnet_material, container, false);
        findViewById();
        return view;
    }

    private void findViewById() {
        initheader();
        ininListView();
        //导入Excel
        layoutMainView = (LinearLayout) view.findViewById(R.id.fm_lay_mainView);
        layButt = (LinearLayout) view.findViewById(R.id.design_view);
        RadioButton impIv = (RadioButton) view.findViewById(R.id.m_tv_choosefile);
        ImageView modelIv = (ImageView) view.findViewById(R.id.m_tv_show_model);
        errNumTv = (TextView) view.findViewById(R.id.m_tv_errNum);
        impIv.setOnClickListener(this);
        modelIv.setOnClickListener(this);
        errNumTv.setOnClickListener(this);

        sync_button = (TextView) view.findViewById(R.id.design_continue_button);
        SetTypeface.set(sync_button, IconSourse.TONGBU);

        sync_button.append(" 提交项目材料");
        sync_button.setOnClickListener(this);
        layButt.setVisibility(View.GONE);
        refreshListView.setCanScroll(true);
    }

    private void initheader() {
        headsecond_layout = (HeadSecondControlPanel) view.findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(IconSourse.ADD + "",
                View.GONE, R.color.bar_right, ListenerSet.back, "", R.color.title,
                View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));

        String projectName = String.valueOf(MyApp.currProject.getProject_name()).trim();
        if (!projectName.contains("null") || !projectName.isEmpty()) {
            headsecond_layout.setSearchTitle(projectName);
        }
    }

    private void ininListView() {
        arrayList = new ArrayList<>();
        fileList_QQ = new ArrayList<>();
        fileList_WX = new ArrayList<>();

        refreshListView = (SwipeRefreshListView) view.findViewById(R.id.material_srlview);
        refreshListView.setOnRefreshListener(this);
        refreshListView.setFragment(this);

        detailList = new ArrayList<>();
        adaptermaterial = new Adapter_FragMaterial(getActivity(), detailList);
        refreshListView.setAdapter(adaptermaterial);
    }

    //下拉
    @Override
    public void onRefresh() {
        if (!isRefresh) {
            refreshListView.setRefreshing(false);
            return;
        }
        startNum = 0;
        addNum = 15;
        getCodeSetList(1);
    }

    //上拉
    @Override
    public void addMore() {
        if (!MyApp.NetWorkConnect) {
            refreshListView.setRefreshing(false);
            refreshListView.removeFooterView();
            return;
        }
        super.addMore();
        startNum = addNum;
        addNum += MyApp.addNum;
        getCodeSetList(HttpStringUtil.ADDMROE);
    }

    private void getCodeSetList(int code) {
        String name = MyApp.currProject.getProject_name().trim();
        if (name.isEmpty()) return;
        String versionId = MyApp.currProject.getCodeset_version_id().trim();
        if (versionId.isEmpty()) {
            showToast("请先手动上传项目材料");
            return;
        }
        if (code == 11) {
            MyApp.HTTP.getMaterialList1(handler, 11, "", "", versionId, 0, 999);
        } else {
            MyApp.HTTP.getMaterialList1(handler, code, "", "", versionId, startNum, addNum);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 9090 && resultCode == Activity.RESULT_OK) {
            typeList = data.getStringArrayListExtra("result");
            for (MaterialDetail materialDetail : detailList) {
                if (typeList.contains(materialDetail.getType())) {
                    materialDetail.setSort(typeList.indexOf(materialDetail.getType()));
                }
            }
            isSetType = true;
            final String projectName = String.valueOf(headsecond_layout.stitle.getText()).trim();
            if (projectName.isEmpty()) {
                showToast("请先选择项目！");
                return;
            }
            upData(projectName);
        } else if (resultCode == Activity.RESULT_OK) {
            isRefresh = false;
            type = 1;
            if (requestCode != 2) return;
            Uri uri = data.getData();
            String valueOf = String.valueOf(uri.getPath());
            if (!valueOf.endsWith(".xls")) {
                showToast("仅支持97-03 xls格式的Excel");
                return;
            }
            try {
                File file = new File(new URI(uri.toString()));
                dellFile(file);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<MaterialDetail> errList;
    public static List<MaterialDetail> yesList;
    public static ArrayList<String> typeList;
    public static Map<String, String> map;

    //导入excel材料
    private void dellFile(File file) {
        isRefresh = false;
        type = 1;
        List<MaterialDetail> read2DB = jxlUtil.read2DB(file);
        if (read2DB.isEmpty()) {
            showToast("无数据导入");
            return;
        }
        detailList.clear();
        map = new HashMap<>();
        String result;
        boolean isAdd;
        errList = new ArrayList<>();
        yesList = new ArrayList<>();
        typeList = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (MaterialDetail detailSys : read2DB) {
            isAdd = true;
            result = "";
            String number = detailSys.getMaterial_number().trim();//64
            String type = detailSys.getType().trim();
            String name = detailSys.getName().trim();//64
            String spec = detailSys.getSpec().trim();//100
            String num = detailSys.getNum().trim();//6
            String unit = detailSys.getUnit().trim();//32
            int sort = 0;
            if (type.isEmpty()) {
                isAdd = false;
                result = "物料分类不能为空";
            } else {
                if (!typeList.contains(type)) {
                    typeList.add(type);
                }
                sort = typeList.indexOf(type);
                detailSys.setSort(sort);
            }
            if (number.isEmpty()) {
                isAdd = false;
                result = "物料编码不能为空";
            } else {
                if (names.contains(number)) {
                    isAdd = false;
                    result += "/物料编码重复";
                } else {
                    names.add(number);
                }
            }
            if (name.isEmpty()) {
                isAdd = false;
                result += "/名称不能为空";
            }
            if (num.isEmpty()) {
                isAdd = false;
                result += "/未录入数量";
            } else {
                if (num.contains(".")) {
                    try {
                        Double.parseDouble(num);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        isAdd = false;
                        result += "/数量格式不对";
                    }
                } else {
                    if (!TextUtils.isDigitsOnly(num)) {
                        isAdd = false;
                        result += "/数量格式不对";
                    }
                }
            }
            if (name.length() > 64) {
                isAdd = false;
                result += "/名称大于64个字";
            }
            if (spec.length() > 100) {
                isAdd = false;
                result += "/规格型号大于100个字";
            }
            if (unit.length() > 32) {
                isAdd = false;
                result += "/单位长度大于32个字";
            }
            if (number.length() > 64) {
                isAdd = false;
                result += "/物料编码大于64个字";
            }
            if (isAdd) {
                detailSys.setNum(String.valueOf(Double.valueOf(num)));
                detailList.add(detailSys);
            } else {
                map.put(detailSys.getUuid(), result);
                errList.add(detailSys);
            }
        }
        yesList.addAll(detailList);
        errNumTv.setText("错/全：" + errList.size() + "/" + read2DB.size());
        refreshListView.update();
        refreshListView.setCanScroll(false);
        layButt.setVisibility(View.VISIBLE);
    }

    private void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        String projectName = MyApp.currProject.getProject_name();
        switch (type) {
            case 0://切换项目时刷新数据
                String trim = String.valueOf(headsecond_layout.stitle.getText()).trim();
                if (projectName.isEmpty() || projectName.equals("null")) return;
                if (!projectName.equals(trim)) headsecond_layout.setSearchTitle(projectName);
                startNum = 0;
                addNum = 15;
                getCodeSetList(1);
                break;
            case 1://导入项目材料时不刷新数据
                break;
            case 2://第一次进入时：有名称才刷数据
                if (projectName.isEmpty() || projectName.equals("null")) return;
                startNum = 0;
                addNum = 15;
                getCodeSetList(1);
                break;
        }
    }

    private List<File> fileList_QQ, fileList_WX;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.m_tv_choosefile://导入Excel
                if (!isArrowAdd) {
                    ToastUtils.showToast(getActivity(), "您已有材料数据，不能导入新的材料");
                    return;
                }
                importMaterials();
                break;
            case R.id.design_continue_button://提交材料
                final String projectName = String.valueOf(headsecond_layout.stitle.getText()).trim();
                if (projectName.isEmpty()) {
                    showToast("请先选择项目！");
                    return;
                }
                if (sync_button.getText().toString().equals("添加新的材料")) {
                    startActivity(new Intent(getActivity(), AddNewMaterial.class));
                } else {
                    if (errList.isEmpty()) {
                        if (!isSetType) {
                            DialogUtils.showMsgDialog(getActivity(), "是否设置分类排序？", "如果不设置分类排序则分类排序将默认以导入先后顺序排序。", "设置", "直接上传", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(getActivity(), SettingTypeActivity.class);
                                    intent.putParcelableArrayListExtra("result", detailList);
                                    startActivityForResult(intent, 9090);
                                }
                            }, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    upData(projectName);
                                }
                            });
                        } else {
                            upData(projectName);
                        }
                    } else
                        showToast("所有材料必须正确，请修改错误");
                }

                break;
            case R.id.m_tv_show_model://查看模版
                IntentToActivity.intent(getActivity(), ShowBigImageActivity1.class);
                break;
            case R.id.m_tv_errNum://处理导入错误数据
                if (errList != null && !errList.isEmpty()) {
                    FixMaterialFaultDialog dialog = new FixMaterialFaultDialog();
                    dialog.setHandler(handler);
                    dialog.setCancelable(false);
                    dialog.show(getFragmentManager(), "2");
                } else {
                    showToast("数据正常，可以提交");
                }
                break;
        }
    }

    private void importMaterials() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                fileList_QQ.clear();
                fileList_WX.clear();
                File[] files = null, files2 = null;
                try {
                    File skRoot = Environment.getExternalStorageDirectory();//获取SD卡根目录
//                    File skRoot2 = Environment.getRootDirectory();//获取手机根目录
                    files = skRoot.listFiles();
//                    files2 = skRoot2.listFiles();
                } catch (Exception e) {
                    showToast(e.getMessage());
                }
                if (files != null) fileForEach(files);
//                if (files2 != null) fileForEach(files2);
                arrayList.clear();
                arrayList.add("微信接收的文件");
                arrayList.add("QQ接收的文件");
                arrayList.add("其他位置文件");
                handler.sendEmptyMessage(10);
            }
        }).start();
    }

    private void fileForEach(File[] files) {
        for (File file : files) {
            if (file.getName().equals("tencent")) {
                for (File file2 : file.listFiles()) {
                    String file2Name = file2.getName();
                    if (file2Name.equals("QQfile_recv")) {
                        for (File file3 : file2.listFiles()) {
                            if (file3.getName().endsWith(".xls") && !fileList_QQ.contains(file3)) {
                                fileList_QQ.add(file3);
                            }
                        }
                    } else if (file2Name.equals("MicroMsg")) {
                        for (File file4 : file2.listFiles()) {
                            if (file4.getName().equals("Download")) {
                                for (File file5 : file4.listFiles()) {
                                    if (file5.getName().endsWith(".xls") && !fileList_WX.contains(file5)) {
                                        fileList_WX.add(file5);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void upData(String projectName) {
        showWaitDialog(-1, "处理中...");
        RequestParams params = new RequestParams();
        params.addBodyParameter("pro_id", MyApp.currProject.getStage_id());
        params.addBodyParameter("pro_name", projectName);
        String jsonString = JSON.toJSONString(detailList);
        params.addBodyParameter("material_all", jsonString);
        MyApp.HTTP.uploadProjectMateial(handler, params);
    }

    @Override
    public void onDestroyView() {
        map = null;
        errList = null;
        yesList = null;
        super.onDestroyView();
    }

    boolean isSetType = false;//是否设置分类排序
}
